{% extends "base.html" %}

{% block scripts %}
	{{ parent() }}
	<script src="{{ settings.assets_url }}javascript/chartjs/chart.core.js"></script>
	<script src="{{ settings.assets_url }}javascript/chartjs/chart.line.js"></script>
{% endblock %}
{% block title %}Manage your Server{% endblock %}

{% block servername %}
<ul class="nav navbar-nav">
	<li class="active dynUpdate" id="{{ server.id }}"><a><i id="applyUpdate" class="fa fa-circle-o-notch fa-spinner fa-spin"></i> {{ server.name }}</a></li>
</ul>
{% endblock %}

{% block sidebar %}
<div class="list-group">
	<a href="#" class="list-group-item list-group-item-heading"><strong>{{ lang.sidebar_acc_actions }}</strong></a>
	<a href="../account.php" class="list-group-item">{{ lang.sidebar_settings }}</a>
	<a href="../totp.php" class="list-group-item">TOTP {{ lang.sidebar_settings }}</a>
	<a href="../servers.php" class="list-group-item">{{ lang.sidebar_servers }}</a>
</div>
<div class="list-group">
	<a href="#" class="list-group-item list-group-item-heading"><strong>{{ lang.sidebar_server_acc }}</strong></a>
	<a href="index.php" class="list-group-item active">{{ lang.sidebar_overview }}</a>
	<a href="files/index.php" class="list-group-item">{{ lang.sidebar_files }}</a>
	{% if permission.users.view == true %}<a href="users/list.php" class="list-group-item">Manage Subusers</a>{% endif %}
	<a href="settings.php" class="list-group-item">{{ lang.sidebar_manage }}</a>
	<a href="plugins/index.php" class="list-group-item">{{ lang.sidebar_plugins }}</a>
</div>
{% endblock %}

{% block content %}
<div class="col-9">
	<ul class="nav nav-tabs" id="config_tabs">
		<li class="active"><a href="#stats" data-toggle="tab">Statistics</a></li>
		{% if permission.console.view == true %}<li><a href="#console" data-toggle="tab">Control Server</a></li>{% endif %}
	</ul><br />
	<div class="tab-content">
		<div class="tab-pane active" id="stats">
			<div class="row">
				<div class="col-6">
					<h3 class="nopad">Memory Usage</h3><hr />
					<div class="row">
						<canvas id="memoryChart" width="300" height="150"></canvas>
					</div>
				</div>
				<div class="col-6">
					<h3 class="nopad">CPU Usage</h3><hr />
					<div class="row">
						<canvas id="cpuChart" width="300" height="150"></canvas>
					</div>
				</div>
			</div>
			<div class="col-12">
				<h3>{{ lang.node_overview_information_h1 }}</h3><hr />
				<table class="table table-striped table-bordered table-hover">
					<tbody>
						<tr>
							<td><strong>{{ lang.string_connection }}</strong></td>
							<td>{{ server.server_ip }}:{{ server.server_port }}</td>
						</tr>
						<tr>
							<td><strong>{{ lang.string_node }}</strong></td>
							<td>{{ server.node }}</td>
						</tr>
						<tr>
							<td><strong>{{ lang.string_mem_alloc }}</strong></td>
							<td>{{ server.max_ram }} MB</td>
						</tr>
						<tr>
							<td><strong>{{ lang.string_disk_alloc }}</strong></td>
							<td>{{ server.disk_space }} MB</td>
						</tr>
					</tbody>
				</table>
			</div>
		</div>
		{% if permission.console.view == true %}
			<div class="tab-pane" id="console">
				<div class="col-12">
					<textarea id="live_console" class="form-control console" readonly="readonly">{{ server.console_inner }}</textarea>
				</div>
				<div class="col-6">
					<hr />
					{% if permission.console.commands == true %}
						<form action="#" method="post" id="console_command">
							<fieldset>
								<div class="input-group">
									<input type="text" class="form-control" name="command" id="ccmd" placeholder="{{ lang.node_console_command_help }}" />
									<span class="input-group-btn">
										<button id="sending_command" class="btn btn-primary">&rarr;</button>
									</span>
								</div>
							</fieldset>
						</form>
						<div class="alert alert-danger" id="sc_resp" style="display:none;margin-top: 15px;"></div>
					{% endif %}
				</div>
				<div class="col-6" style="text-align:center;">
					<hr />
					{% if permission.console.power == true %}
						<button class="btn btn-primary btn-sm start" id="on">{{ lang.string_start }}</button>
						<button class="btn btn-primary btn-sm poke" id="restart">{{ lang.string_restart }}</button>
						<button class="btn btn-danger btn-sm poke" id="off">{{ lang.string_stop }}</button>
						<button class="btn btn-primary btn-sm poke" data-toggle="modal" data-target="#pauseConsole" id="pause_console"><small><i class="fa fa-pause"></i></small></button>
						<div id="pw_resp" style="display:none;margin-top: 15px;"></div>
					{% endif %}
				</div>
			</div>
		{% endif %}
	</div>
</div>
<div class="modal fade" id="pauseConsole" tabindex="-1" role="dialog" aria-labelledby="PauseConsole" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
				<h4 class="modal-title" id="PauseConsole">{{ lang.node_console_scrollstop_h1|raw }}</h4>
			</div>
			<div class="modal-body">
				<div class="row">
					<div class="col-1"></div>
					<div class="col-10">
						<textarea id="paused_console" class="form-control console" readonly="readonly"></textarea>
					</div>
					<div class="col-1"></div>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">{{ lang.string_close }}</button>
			</div>
		</div>
	</div>
</div>
<script type="text/javascript">
	$(document).ready(function(){
		var socket = io('http://{{ node.ip }}:{{ node.gsd_console }}/{{ server.gsd_id }}', {'query': 'token={{ server.gsd_secret }}'});
		var ctx = $("#memoryChart").get(0).getContext("2d");
		var cty = $("#cpuChart").get(0).getContext("2d");
		var memoryChartData={labels:["","","","","","","","","",""],datasets:[{label:"Memory Usage",fillColor:"rgba(220,220,220,0.2)",strokeColor:"rgba(220,220,220,1)",pointColor:"rgba(220,220,220,1)",pointStrokeColor:"#fff",pointHighlightFill:"#fff",pointHighlightStroke:"rgba(220,220,220,1)",data:[0,0,0,0,0,0,0,0,0,0]}]};var cpuChartData={labels:["","","","","","","","","",""],datasets:[{label:"CPU Usage",fillColor:"rgba(220,220,220,0.2)",strokeColor:"rgba(220,220,220,1)",pointColor:"rgba(220,220,220,1)",pointStrokeColor:"#fff",pointHighlightFill:"#fff",pointHighlightStroke:"rgba(220,220,220,1)",data:[0,0,0,0,0,0,0,0,0,0]}]};
		var memoryChart = new Chart(ctx).Line(memoryChartData, {tooltipTemplate: {% verbatim %}"<%= value %> Mb"{% endverbatim %}});
		var cpuChartData = new Chart(cty).Line(cpuChartData, {tooltipTemplate: {% verbatim %}"<%= value %> %"{% endverbatim %}});
		socket.on('process', function (data) {
			var currentTime = new Date();
			memoryChart.addData([parseInt(data.process.memory / (1024 * 1024))], "");memoryChart.removeData();
			cpuChartData.addData([data.process.cpu], "");cpuChartData.removeData();
		});
		// socket.on('query', function(data){
		// 	if($("#players_notice").is(":visible")){
		// 		$("#players_notice").hide();
		// 		$("#toggle_players").show();
		// 	}
		// 	if(data.query.players.length !== 0){
		// 		$("#toggle_players").html("");
		// 		$.each(data.query.players, function(id, name) {
		// 			$("#toggle_players").append('<img data-toggle="tooltip" src="http://i.fishbans.com/helm/'+name+'/32" title="'+name+'" style="padding: 0 2px 6px 0;"/>');
		// 		});
		// 	}else{
		// 		$("#toggle_players").html('<p class="text-muted">No players are currently online.</p>');
		// 	}
		// 	$("img[data-toggle='tooltip']").tooltip();
		// });
		{% if permission.console.view == true %}
			socket.on('console', function (data) {
				$("#live_console").val($("#live_console").val() + data.l);
				$('#live_console').scrollTop($('#live_console')[0].scrollHeight - $('#live_console').height());
			});
			$("#pause_console").click(function(){
				$("#paused_console").val();
				$("#paused_console").val($("#live_console").val());
			});
			$('#live_console').scrollTop($('#live_console')[0].scrollHeight - $('#live_console').height());
			{% if permission.console.commands == true %}
				$("#console_command").submit(function(event){
					event.preventDefault();
					var ccmd = $("#ccmd").val();
					if(ccmd != ""){
						$("#sending_command").html('<i class="fa fa-refresh fa-spin"></i>').addClass('disabled');
						$.ajax({
							type: "POST",
							headers: {"X-Access-Token": "{{ server.gsd_secret }}"},
							url: 'http://{{ node.ip }}:{{ node.gsd_listen }}/gameservers/{{ server.gsd_id }}/console',
							timeout: 5000,
							data: { command: ccmd },
							error: function(jqXHR, textStatus, errorThrown) {
								$("#sc_resp").html('Unable to process your request. Please try again.').fadeIn().delay(5000).fadeOut();
								$("#sending_command").removeClass('disabled');
								$("#sending_command").html('&rarr;');
								$("#ccmd").val('');
							},
							success: function(data) {
								$("#sending_command").removeClass('disabled');
								$("#sending_command").html('&rarr;');
								$("#ccmd").val('');
									if(data != ""){
										$("#sc_resp").html(data).fadeIn().delay(5000).fadeOut();
									}
							}
						});
					}
				});
			{% endif %}
			{% if permission.console.power == true %}
				var can_run = true;
				$(".poke").click(function(){
					var command = $(this).attr("id");
					if(command == 'off'){ uCommand = 'Stopping'; }else{ uCommand = 'Restarting';}
						if(can_run === true){
							can_run = false;
							$(this).append(' <i class="fa fa-refresh fa-spin"></i>');
							$(this).toggleClass('disabled');
							$.ajax({
								type: "GET",
								headers: {"X-Access-Token": "{{ server.gsd_secret }}"},
								url: 'http://{{ node.ip }}:{{ node.gsd_listen }}/gameservers/{{ server.gsd_id }}/off',
								timeout: 5000,
								error: function(jqXHR, textStatus, errorThrown) {
									$("#pw_resp").attr('class', 'alert alert-danger').html('Unable to process your request. Please try again. ('+ errorThrown +')').fadeIn().delay(5000).fadeOut();
									$("#off").removeClass('disabled');
									$("#off").html('Stop');
									$("#restart").removeClass('disabled');
									$("#restart").html('Restart');
									can_run = true;
									return false;
								},
								success: function(data) {
									if(data == "ok"){
										$("#pw_resp").attr('class', 'alert alert-success').html("Server has been stopped successfully.").fadeIn().delay(5000).fadeOut();
										can_run = true;
										if(command == "restart"){
											setTimeout(function() { start_server(); }, 5000)
										}
										$("#off").removeClass('disabled');
										$("#off").html('{{ lang.string_stop }}');
										return false;
									}
								}
							});
						}else{
							return false;
						}
				});
				$("#on").click(function(){
					start_server();
				});
				function start_server() {
					if(can_run === true){
						can_run = false;
						$("#restart").removeClass('disabled');
						$("#restart").html('{{ lang.string_restart }}');
						$("#on").append(' <i class="fa fa-refresh fa-spin"></i>');
						$("#on").toggleClass('disabled');
						$.ajax({
							type: "GET",
							url: "ajax/console/power.php",
							timeout: 5000,
							error: function(jqXHR, textStatus, errorThrown) {
								$("#pw_resp").attr('class', 'alert alert-danger').html('{{ lang.node_ajax_generic_error }} ('+ errorThrown +')').fadeIn().delay(5000).fadeOut();
								$("#on").removeClass('disabled');
								$("#on").html('Start');
								can_run = true;
								return false;
							},
							success: function(data) {
								if(data == "ok"){
									$("#pw_resp").attr('class', 'alert alert-success').html("{{ lang.node_console_ajax_server_started }}").fadeIn().delay(5000).fadeOut();
									can_run = true;
								}else{
									$("#pw_resp").attr('class', 'alert alert-danger').html(data).fadeIn().delay(5000).fadeOut();
									can_run = true;
								}
								$("#on").toggleClass('disabled');
								$("#on").html('{{ lang.string_start }}');
							}
						});
					}else{
						return false;
					}
				}
			{% endif %}
		{% endif %}
	});
</script>
{% endblock %}
